<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="main.css">
    <title>博客编辑</title>
    <style type="text/css">
        .title-wrapper {
            margin-bottom: 10px
        }
    </style>
</head>

<body>
<h1 style="border-bottom: 1px solid #ccc; padding-bottom: 10px;">编辑博客</h1>
<div>
    <div class="title-wrapper">
        <input id="text-title">
    </div>
    <div class="content-wrapper">
        <textarea id="text-content"></textarea>
    </div>
    <div>
        <button id="btn-update">保存</button>
    </div>
</div>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script type="text/javascript">
    /*发送get请求*/
    function get(url) {
        return $.get(url);
    }

    /*发送post请求*/
    function post(url, data = {}) {
        return $.ajax({
            type: 'post',
            url,
            data: JSON.stringify(data),
            contentType: 'application/json'
        })
    }

    /*获取 url 参数*/
    function getUrlParams() {
        let paramStr = location.href.split('?')[1] || '';
        paramStr = paramStr.split('#')[0];
        const result = {};
        paramStr.split('&').forEach(itemStr => {
            const arr = itemStr.split('=');
            const key = arr[0];
            result[key] = arr[1];
        });
        return result;
    }

    /*获取 dom 元素*/
    const $textTitle = $('#text-title');
    const $textContent = $('#text-content');
    const $btnUpdate = $('#btn-update');

    /*获取博客内容*/
    const urlParams = getUrlParams();
    let id = urlParams.id;
    const url = '/api/blog/detail?id=' + id;
    get(url).then(res => {
        if (res.errno !== 0) {
            alert('操作错误');
            return;
        }
        /*显示数据*/
        const data = res.data || {};
        $textTitle.val(data.title);
        $textContent.val(data.content);
        $btnUpdate.attr('data-id', data.id);
    });

    /*提交修改内容*/
    $btnUpdate.click(() => {
        const title = $textTitle.val().trim();
        const content = $textContent.val().trim();
        const url = '/api/blog/update?id=' + id;
        const data = {title, content};
        post(url, data).then(res => {
            if (res.errno !== 0) {
                alert('操作错误');
                return;
            }
            alert('更新成功');
            location.href = '/admin.html';
        });
    });

</script>
</body>

</html>